// 文件上传和下载操作
// @author: caoshi
// @date: 2021-05-13 19:52
package main

import (
	"fmt"
	"html/template"
	"io/fs"
	"io/ioutil"
	"net/http"
	"strings"
)

/**
	展示文件上传的页面
 */
func fileUploadTest(w http.ResponseWriter, r *http.Request) {
	temp, _ := template.ParseFiles("view/index.html")
	temp.Execute(w, nil)
}

// 处理文件上传
func upload(w http.ResponseWriter, r *http.Request) {
	// 用户输入的文件名
	fileName := r.FormValue("fileName")
	file, fileHeader, _ := r.FormFile("file")
	// 原始的文件名
	srcFileName := fileHeader.Filename
	index := strings.LastIndex(srcFileName, ".")
	ext := srcFileName[index:]
	fmt.Println("文件拓展名: ", ext)
	bytes, _ := ioutil.ReadAll(file)
	ioutil.WriteFile("D:/" + fileName + ext, bytes, fs.ModePerm)	// 0777

	// 上传成功后跳转到success.html页面
	temp, _ := template.ParseFiles("view/success.html")
	temp.Execute(w, nil)
}

// 处理文件下载
func download(w http.ResponseWriter, r *http.Request) {
	fileName := r.FormValue("filename")

	file, err := ioutil.ReadFile("F:/godir/" + fileName)
	if err != nil {
		fmt.Println("文件不存在")
		return
	}

	// 设置响应头信息
	header := w.Header()
	header.Set("Content-Type", "application/octet-stream")
	header.Set("Content-Disposition", "attachment;filename=" + fileName)
	// 写入响应对象
	w.Write(file)
}

func main() {
	server := http.Server{Addr: "localhost:8090"}
	http.HandleFunc("/fileUploadTest", fileUploadTest)
	http.HandleFunc("/upload", upload)
	http.HandleFunc("/download", download)
	server.ListenAndServe()
}




